<!doctype html>
<html class="no-js" lang="">
<meta name="viewport" content="width=device-width, initial-scale=1"/>

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>五子棋</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- 可选的 Bootstrap 主题文件（一般不用引入） -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
          integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            crossorigin="anonymous"></script>

    <link rel="apple-touch-icon" href="apple-touch-icon.png">
    <!-- Place favicon.ico in the root directory -->

    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/main1.css">
    <script src="js/danji.js"></script>
    <script src="js/vendor/modernizr-2.8.3.min.js"></script>
</head>

<!--<body style="background-image: url('img/woodfloor.jpg') ; text-align: center;">-->
<body onkeydown="sendmessage()" style="background-color: #f0f0f0 ; text-align: center; ">
<input type="text" id="txt" style="display: block; float: left; margin-left: 30px; margin-top: 80px;">
<div id="contain_in" style="">
    <div style="width: 75%;height: 100%; float: left; display: block; text-align: center;background-color: #f0ad4e">
        <canvas id="myCanvas" width="510px;" height="510px" ; onclick="chessClick(event)">


        </canvas>
    </div>
    <div style="width: 25%; height: 100%; display: block; float: left;text-align: center; background-color: #0a628f">
        <p>

                <button type="button" onclick="restar()" class="btn btn-primary btn-lg" style=" margin-top: 100px;">退出</button>


        </p>
        <p>
            <button type="button" class="btn btn-primary btn-lg" onclick="undo()" style=" margin-top: 100px;">悔棋
            </button>


        </p>
        <p>

                <button type="button" class="btn btn-primary btn-lg"   style=" margin-top: 100px;">重新开始</button>



        </p>

    </div>
<div>
    <textarea id="content" name="content" rows="10" cols="75"
              onpropertychange="if(this.scrollHeight>80) this.style.posHeight=this.scrollHeight+5"  readonly="readonly" style="width: 50%;height: 100%; display: block;float: left"></textarea>
    <div style="width: 50%;height: 100%;display: block;float: right">
        请输入聊天内容：<br>
        <input type="text" id="firstname" name="firstname"  style="width: 100%; height: 50%">
    <button type="button" class="btn btn-primary btn-lg btn-block" onclick="sendmessage()">发送</button>
        <button type="button" class="btn btn-primary btn-lg btn-block" onclick="">举报</button>
    </div>
</div>


</div>



<script type="text/javascript">

    window.onload=function(){
        document.onkeydown=function(){
            var e=window.event||arguments[0];
            if(e.keyCode==123){
                return false;
            }else if((e.ctrlKey)&&(e.shiftKey)&&(e.keyCode==73)){  //禁止审查元素
                return false;
            }
        };
        document.oncontextmenu=function(){
            return false;
        }
    }
    var a1;
    var b1;
    var a2;
    var b2;
    var websocket = null;
    var isclick = true;
    var imgwhile = new Image();
    imgwhile.src = "img/keleyiw.png";
    var imgblack = new Image();
    imgblack.src = "img/keleyib.png";
    var chessData = [];
    var isblack = true;
    var canvas = document.getElementById("myCanvas")
    var canvass = document.getElementById("myCanvas")
    var ctn = canvas.getContext('2d');
    var ctnbw = canvass.getContext('2d');
    var solid = 34;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/websocket");
        //websocket = new WebSocket("ws://192.168.123.222:8080/websocket");
    }
    else {
        alert('当前浏览器 Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        setMessageInnerHTML("WebSocket连接成功");
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        var getstring = event.data;
        // alert(getstring)
        var fdStart = getstring.indexOf("&");
        var fdStart2 = getstring.indexOf("!");
        var fdStart3 = getstring.indexOf("w");
        var fdStart4 = getstring.indexOf("b");
        if (fdStart3==0){
            getstring = getstring.substr(1);

           var arr1 = getstring.split(",");


            drawChess(2, arr1[0], arr1[1]);//绘制白棋
        }
        if (fdStart4==0) {
            getstring = getstring.substr(1);

            var arr2 = getstring.split(",");


            drawChess(1, arr2[0], arr2[1]);//绘制黑棋
        }

        if (fdStart2 == 0) {
            stopCount();
            document.getElementById('txt').value="现在是己方回合,时限一分钟";
            getstring = getstring.substr(1);
            isclick = true;
            arr = getstring.split(",");
            a2=arr[0];
            b2=arr[1];
            clic(arr[0], arr[1]);
        }
        if (fdStart == 0) {
            // 表示strCode是以ssss开头；
            // alert(getstring)
            getstring = getstring.substr(1);

            document.getElementById("content").innerHTML += "对方：" + getstring + "\n";
            var obj = document.getElementById("content");
            obj.scrollTop = obj.scrollHeight; // good
        }

        if (getstring == "@0") {   //判断是否是悔棋的请求
            if (confirm("对手请求悔棋,是否同意")) {

                websocket.send("@1");
                agreeundo();
                websocket.send("#"+a1 + "," + b1);
                websocket.send("#"+a2 + "," + b2);

            }

            else {

                websocket.send("@2");

            }


        }
        if (getstring=="@8"){
            alert("游戏开始")
            //isclick = true;
        }
        if(getstring=="@1"){
           // alert("对方已同意")
            agreeundo();

        }
         if(getstring=="@2"){
            alert("对方拒绝悔棋")
         }
      if (getstring=="@3"){
            // alert("黑子胜，你败了")
          if (confirm("黑子胜，你败了，是否继续")) {
              location.reload()
          }

          else {
              window.location.href="home.jsp";

          }

      }
      if (getstring=="@4"){
         // alert("白子胜，你败了")
          if (confirm("白子胜，你败了,是否继续")) {
              location.reload()
          }

          else {
              window.location.href="home.jsp";

          }
      }

        // setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("WebSocket连接关闭");
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //    //将消息显示在网页上
    //    function setMessageInnerHTML(innerHTML) {
    //        //  document.getElementById('message').innerHTML += innerHTML + '<br/>';
    //    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {

        //var message = document.getElementById('text').value;
        websocket.send(message);
    }


    for (var i = 0; i <= 510; i += 34) {
        //绘制横线
        ctn.beginPath();
        ctn.moveTo(0, i);
        ctn.lineTo(510, i);
        ctn.closePath();
        ctn.stroke();
        //绘制竖线
        ctn.beginPath();
        ctn.moveTo(i, 0);
        ctn.lineTo(i, 510);
        ctn.closePath();
        ctn.stroke();
    }

    ctn.fillStyle = "#000";//填充canvas的背景颜色
    ctn.fillRect(3 * solid - 6, 3 * solid - 6, 12, 12);//参数分别表示 x轴,y轴,宽度,高度
    ctn.fillRect(12 * solid - 6, 3 * solid - 6, 12, 12);
    ctn.fillRect(7 * solid - 6, 7 * solid - 6, 12, 12);
    ctn.fillRect(3 * solid -6, 12 * solid - 6, 12, 12);
    ctn.fillRect(12 * solid - 6, 12 * solid - 6, 12, 12);
    ctn.lineWidth = 1;//边框宽度

    //初始化棋盘数组
    for (var x = 0; x < 15; x++) {
        chessData[x] = [];
        for (var y = 0; y < 15; y++) {
            chessData[x][y] = 0;
        }

    }

    function chessClick(e) {
        if(isclick){

            x = e.offsetX

            y = e.offsetY
            x = Math.round(x / solid);//相对canvas的x坐标
            y = Math.round(y / solid);
            var m ="!"+ x + "," + y;

            if(chessData[x][y]==0){
                if (x>0&&x<15&&y>0&&y<15){
                    isclick=false;
                }
                a1=x;
                b1=y;
                websocket.send(m);

                stopCount();
                timedCount();
                clic(x, y);
            }




        }


    }

    function clic(x, y) {


        //alert(x)


        // alert(x+"  "+y+"  "+cleft+"  "+ctop);

        //  alert()
        //console.log(x+""+y);

        //alert(x+"  "+y);


//        ctn.fillStyle="#fff000";
//        ctn.beginPath();
//        ctn.arc(x, y , solid/2, 0, Math.PI * 2, true);
//        ctn.closePath();
//        ctn.fill();

        // ctn.drawImage(imgblack,x-17,y-17);
        if (chessData[x][y] == 1 || chessData[x][y] == 2 ) {

            return;
        }

        if (isblack) {//判断是否该黑色的点

            drawChess(1, x, y);//绘制黑棋

        } else {
            drawChess(2, x, y); //绘制白棋
        }
    }

    function drawChess(chess, x, y) {

        if (x > 0 && x < 15 && y > 0 && y < 15) {


            if (chess == 1) {
                // alert(x+" "+y);
                isblack = false;
                ctnbw.drawImage(imgblack, x * 34 - 17, y * 34 - 17);
                chessData[x][y] = 1;

                count(chess, x, y);


            }

            if (chess == 2) {
                isblack = true;
                ctnbw.drawImage(imgwhile, x * 34 - 17, y * 34 - 17);
                chessData[x][y] = 2;
                count(chess, x, y);

            }

        }


    }

    function count(chess, x, y) {  //计算胜负



        var hz = 0;
        var ve = 0;
        var ls = 0;
        var rs = 0;
        //计算水平方向hz是否够五个

        for (var i = x; i > 0; i--) {   //计算点击处左边的相同棋子的数量

            if (chessData[i][y] != chess) {//判断右边是否有其他的颜色棋子

                break;
            }

            hz++;


        }

        for (var i = x + 1; x < 15; i++) {
            if (chessData[i][y] != chess) {
                break;
            }
            hz++;
        }

        for (var i = y; i > 0; i--) {      // //计算上下方向的输赢
            if (chessData[x][i] != chess) {
                break;
            }
            ve++;
        }
        for (var i = y + 1; i < 15; i++) {
            if (chessData[x][i] != chess) {
                break;
            }
            ve++;
        }
        for (var i = x, j = y; i > 0, j > 0; i--, j--) {   //判断左上右下的棋子
            if (chessData[i][j] != chess) {
                break;
            }
            ls++;
        }
        for (var i = x + 1, j = y + 1; i < 15, j < 15; i++, j++) {
            if (chessData[i][j] != chess) {
                break;
            }
            ls++;
        }

        for (var i = x, j = y; i < 15, j > 0; i++, j--) {
            if (chessData[i][j] != chess) {
                break;
            }
            rs++;
        }
        for (var i = x - 1, j = y + 1; i > 0, j < 15; i--, j++) {
            if (chessData[i][j] != chess) {
                break;
            }
            rs++;
        }
      // alert("左右"+hz+"上下"+ve)
        if (hz >= 5 || ve >= 5 || ls >= 5 || rs >= 5) {
            websocket.send("b"+"."+x+"."+y);
            if (chess == 1) {
                firm(1);

                //alert("黑棋胜,请刷新重玩")
            } else {
                websocket.send("w"+"."+x+"."+y);
                firm(2);
            }


        }

    }

    function firm(chess) {

        if (chess == 1) {
            if (confirm("黑棋胜，是否刷新重玩")) {

                location.reload();

            }

            else {

                canvas.onclick = function () {
                    canvas.disabled = 'disabled';
                };

            }
        } else {

            if (confirm("白棋胜，是否刷新重玩")) {

                location.reload();

            }

            else {

                canvas.onclick = function () {
                    canvas.disabled = 'disabled';
                };

            }


        }


    }
    function sendmessage(){
        if(event.keyCode==13){
            var txt = document.getElementById("firstname").value;
            document.getElementById("firstname").value="";
            document.getElementById("content").innerHTML +="我："+txt+"\n";
            websocket.send("&"+txt);
        }


      //  document.getElementById("content").innerHTML+=txt+"\n";

        var obj = document.getElementById("content");
        obj.scrollTop = obj.scrollHeight; // good




    }
    function undo() {

         websocket.send("@0");

   }
   function  agreeundo() { //同意悔棋
       chessData[a1][b1]=0;
       chessData[a2][b2]=0;
       ctn.clearRect(a1*solid-solid/2,b1*solid-solid/2,34,34);
       //绘制横线
       ctn.beginPath();
       ctn.moveTo(a1*solid-solid/2, b1*solid);
       ctn.lineTo(a1*solid+solid/2, b1*solid);
       ctn.closePath();
       ctn.stroke();

       ctn.clearRect(a2*solid-solid/2,b2*solid-solid/2,34,34);
       //绘制横线
       ctn.beginPath();
       ctn.moveTo(a2*solid-solid/2, b2*solid);
       ctn.lineTo(a2*solid+solid/2, b2*solid);
       ctn.closePath();
       ctn.stroke();

       //绘制竖线
       ctn.beginPath();
       ctn.moveTo(a1*solid,  b1*solid-solid/2);
       ctn.lineTo(a1*solid,  b1*solid+solid/2);
       ctn.closePath();
       ctn.stroke();
       if (a1==3&&b1==3||a1==12&&b1==3||a1==7&&b1==7||a1==3&&b1==12||a1==12&&b1==12){
           ctn.fillStyle = "#000";//填充canvas的背景颜色
           ctn.fillRect(a1*solid-6, b1*solid-6, 12, 12);//参数分别表示 x轴,y轴,宽度,高度
           ctn.lineWidth = 1;//边框宽度
       }



       //绘制竖线
       ctn.beginPath();
       ctn.moveTo(a2*solid,  b2*solid-solid/2);
       ctn.lineTo(a2*solid,  b2*solid+solid/2);
       ctn.closePath();
       ctn.stroke();
       if (x==3&&y==3||x==12&&y==3||x==7&&y==7||x==3&&y==12||x==12&&y==12){
           ctn.fillStyle = "#000";//填充canvas的背景颜色
           ctn.fillRect(a2*solid-6, b2*solid-6, 12, 12);//参数分别表示 x轴,y轴,宽度,高度
           ctn.lineWidth = 1;//边框宽度
       }
   }

    function  restar(){

        if (confirm("退出后当认输处理,是否同意")) {
            websocket.send("@6");
            window.location.href="home.jsp";

        }else{

        }

        //window.history.back(-1);
    }


var c=60;
var t;
function timedCount()
{
    if(c==1){
          alert("对方游戏超时，你赢了");
          stopCount();
        websocket.send("@7");

    }
    document.getElementById('txt').value="对方回合倒计时："+c;
    c=c-1;
    t=setTimeout("timedCount()",1000)
}
function stopCount()
{
    c=60;
    setTimeout("document.getElementById('txt').value=0",0);
    clearTimeout(t);
}
</script>


<!--<button onclick="send()">发送消息</button>-->
<!--<hr/>-->
<!--<button onclick="closeWebSocket()">关闭WebSocket连接</button>-->
<!--<hr/>-->
<!--<div id="message"></div>-->
</body>

</html>